package bio.five;

import java.io.*;
import java.net.Socket;

/*
    服务端处理接收消息的线程
 */
public class HandlerAcceptThread extends Thread {
    private Socket socket;

    public HandlerAcceptThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        ) {
            //获取客户端的数据
            String msg = "";
            int len = 0;
            while ((msg = br.readLine()) != null) {
                //将获取到的数据发送给所有客户端
                sendMsgClient(msg);
            }
        } catch (Exception e) {
            //客户端下线
            System.out.println("一个客户端下线了");
            Server.sockets.remove(socket);
        }
    }

    //将消息发送给所有客户端
    public void sendMsgClient(String msg) {
        for(Socket socket:Server.sockets){
            //发送消息
            try {
                OutputStream os = socket.getOutputStream();
                PrintStream ps = new PrintStream(os);
                ps.println(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
